import com.sun.mail.pop3.POP3SSLStore;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;

public class GmailUtils {
    
    private Session session = null;
    private Store store = null;
    private String username, password;
    private Folder folder;
    // This integer keeps track of how many messages are in the inbox from the
    // previous time it checked.
    private int numMessages = -1;
    
    public GmailUtils() {
        
    }
    
    public void setUserPass(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    public void connect() throws Exception {
        Properties pop3Props = new Properties();
        
        pop3Props.setProperty("mail.pop3.socketFactory.class", Constants.SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.ssl.enable", "true");
        pop3Props.setProperty("mail.pop3.port", Integer.toString(Constants.PROTOCOL_PORT));
        pop3Props.setProperty("mail.pop3.socketFactory.port", Integer.toString(Constants.PROTOCOL_PORT));
        
        URLName url = new URLName(Constants.PROTOCOL, Constants.SERVER, Constants.PROTOCOL_PORT, "", username, password);
        GmailAuthenticator gmailAuth = new GmailAuthenticator(username, password);
        
        session = Session.getInstance(pop3Props, gmailAuth);
        store = new POP3SSLStore(session, url);
        store.connect();
        
        if (store.isConnected() && numMessages == -1) {
        	try {
        		openFolder("INBOX");
        		numMessages = getMessageCount();
        	} catch (Exception e) {
        		numMessages = 0;
        	}
        } else {
        	//numMessages = 0;
        }
    }
    
    public boolean isConnected() {
    	return store.isConnected();
    }
    
    public void openFolder(String folderName) throws Exception {
        
        // Open the Folder
        folder = store.getDefaultFolder();
        
        folder = folder.getFolder(folderName);
        
        if (folder == null) {
            throw new Exception("Invalid folder");
        }
        
        // try to open read/write and if that fails try read-only
        try {
            
            folder.open(Folder.READ_WRITE);
            
        } catch (MessagingException ex) {
            
            folder.open(Folder.READ_ONLY);
            
        }
    }
    
    public void closeFolder() throws Exception {
        folder.close(false);
    }
    
    public int getMessageCount() throws Exception {
        return folder.getMessageCount();
    }
    
    public int getNewMessageCount() throws Exception {
    	// If the current number of messages is greater than the last time
    	// we checked, then there was a new message!
        return folder.getMessageCount() - numMessages;
    }
    
    public void disconnect() throws Exception {
    	numMessages = getMessageCount();
        store.close();
    }
    
    public void printMessage(int messageNo) throws Exception {
        System.out.println("Getting message number: " + messageNo);
        
        Message m = null;
        
        try {
            m = folder.getMessage(messageNo);
            dumpPart(m);
        } catch (IndexOutOfBoundsException iex) {
            System.out.println("Message number out of range");
        }
    }
    
    public void printAllMessageEnvelopes() throws Exception {
        
        // Attributes & Flags for all messages ..
        Message[] msgs = folder.getMessages();
        
        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);        
        folder.fetch(msgs, fp);
        
        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" + (i + 1) + ":");
            dumpEnvelope(msgs[i]);
            
        }
        
    }
    
    // Extracts the first line (i.e. all text preceding a newline or carriage
    // return character). Used to identify the useful data in a text message that
    // has other stuff appended to it.
    public String extractFirstLine(int messageNo) throws Exception {
    	String result = null;
        
        try {
            Message m = folder.getMessage(messageNo);
            if (m.isMimeType("text/plain")) {
	            result = (String)m.getContent();
	            int newLineIndex = result.indexOf('\n');
	            int carriageReturnIndex = result.indexOf('\r');
	            int index = Math.min(newLineIndex, carriageReturnIndex);
	            if (index > 0) {
	            	result = result.substring(0, index);
	            }
            } else {
            	result = new String("");            	
            }
        } catch (IndexOutOfBoundsException iex) {
            System.out.println("Message number out of range");
            result = new String("");
        }
        return result;
    	
    }
    
    public String getMessageSender(int messageNo) throws Exception {
    	String sender = null;
    	
    	try {
    		Message m = folder.getMessage(messageNo);
    		Address from[] = m.getFrom();
    		if (from.length > 0) {
    			sender = from[0].toString();
    		} else {
    			System.out.println("Message sender was null.");
    			sender = new String(""); 
    		}
    	} catch (IndexOutOfBoundsException iex) {
            System.out.println("Message number out of range");
            sender = new String("");    		
    	}
    	
    	return sender;
    }
    
    public void printAllMessages() throws Exception {
     
        // Attributes & Flags for all messages ..
        Message[] msgs = folder.getMessages();
        
        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);        
        folder.fetch(msgs, fp);
        
        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" + (i + 1) + ":");
            dumpPart(msgs[i]);
        }
        
    
    }
    
    
    public static void dumpPart(Part p) throws Exception {
        if (p instanceof Message)
            dumpEnvelope((Message)p);
       
        String ct = p.getContentType();
        try {
            pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
            //pr("MESSAGE_BODY: " + )
        } catch (ParseException pex) {
            pr("BAD CONTENT-TYPE: " + ct);
        }
        
        /*
         * Using isMimeType to determine the content type avoids
         * fetching the actual content data until we need it.
         */
        if (p.isMimeType("text/plain")) {
            pr("This is plain text");
            pr("---------------------------");
            String content = (String)p.getContent();
            System.out.println(content); 
            System.out.println("Storing to file:");
            FileUtils.appendToFile(content);
        } else {
            
            // just a separator
            pr("---------------------------");
            
        }
    	
	}

	public static void dumpEnvelope(Message m) throws Exception {        
        pr(" ");
        Address[] a;
        // FROM
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                pr("FROM: " + a[j].toString());
        }
        
        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                pr("TO: " + a[j].toString());                
            }
        }
        
        // SUBJECT
        pr("SUBJECT: " + m.getSubject());
        
        // DATE
        Date d = m.getSentDate();
        pr("SendDate: " +
                (d != null ? d.toString() : "UNKNOWN"));
        

    }
    
    static String indentStr = "                                               ";
    static int level = 0;
    
    /**
     * Print a, possibly indented, string.
     */
    public static void pr(String s) {
        
        System.out.print(indentStr.substring(0, level * 2));
        System.out.println(s);
    }
    
}


